<template>
  <div class="role-manage">
    <!-- 上面的查询框 -->
    <div class="query-form">
      <el-form :inline="true" :model="queryForm" ref="form">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="queryForm.roleName" placeholder="请输入菜单名称" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleQuery">查询</el-button>
          <el-button @click="handleReset('form')">重置</el-button>
        </el-form-item>
      </el-form>
      <div class="action">
        <el-button type="primary" @click="handleCreate">创建</el-button>
      </div>
    </div>
    <!-- 下面的表格 -->
    <div class="base-table">
      <!-- 表单 -->
      <el-table :data="roleList">
        <!-- 列头 -->
        <el-table-column
          v-for="item in columns"
          :key="item.prop"
          :prop="item.prop"
          :label="item.label"
          :formatter="item.formatter"
          :width="item.width"
        >
        </el-table-column>
        <!-- 操作 -->
        <el-table-column label="操作" width="260">
          <template #default="scope">
            <el-button size="mini" @click="handleEdit(scope.row)"
              >编辑</el-button
            >
            <el-button
              type="primary"
              size="mini"
              @click="handleOpenPermission(scope.row)"
              >设置权限</el-button
            >
            <el-button
              type="danger"
              size="mini"
              @click="handleDel(scope.row._id)"
              >删除</el-button
            >
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页 -->
      <el-pagination
        background
        layout="prev, pager, next"
        :total="pager.total"
        @current-change="handleCurrentChange"
        :page-size="pager.pageSize"
        class="el-pagination"
      />
    </div>
    <!-- 弹窗 -->
    <el-dialog title="创建角色" v-model="showModal" @close="handleClose">
      <el-form
        ref="dialogForm"
        :model="roleForm"
        label-width="100px"
        :rules="rules"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            type="textarea"
            :rows="2"
            v-model="roleForm.remark"
            placeholder="请输入备注"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handleClose">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确 定</el-button>
        </span>
      </template>
    </el-dialog>
    <!-- 权限弹窗 -->
    <el-dialog
      title="设置权限"
      v-model="showPermission"
      @close="handlePermissionClose"
    >
      <el-form label-width="100px">
        <el-form-item label="角色名称">{{ curRoleName }}</el-form-item>
        <el-form-item label="选择权限">
          <el-tree
            ref="permissionTree"
            :data="menuList"
            show-checkbox
            node-key="_id"
            :props="{ label: 'menuName' }"
            default-expand-all
          >
          </el-tree>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="handlePermissionClose">取消</el-button>
          <el-button type="primary" @click="handlePermissionSubmit"
            >确 定</el-button
          >
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { formatDate } from '@/utils/date'

export default {
  name: 'Role',
  data() {
    return {
      showModal: false,
      queryForm: {
        roleName: ''
      },
      columns: [
        {
          label: '角色名称',
          prop: 'roleName',
          width: 180
        },
        {
          label: '备注',
          prop: 'remark'
        },
        {
          label: '权限列表',
          prop: 'permissionList',
          formatter: (row, column, value) => {
            let names = []
            let list = value.checkedKeys || []
            list.map(key => {
              if (key) {
                names.push(this.actionMap[key])
              }
            })
            if (!names.length) {
              return '暂未分配任何权限'
            } else {
              return names.join(', ')
            }
          }
        },
        {
          label: '创建时间',
          prop: 'createTime',
          formatter(row, column, value) {
            return formatDate(value)
          }
        },
        {
          label: '更新时间',
          prop: 'updateTime',
          formatter(row, column, value) {
            return formatDate(value)
          }
        }
      ],
      roleList: [],
      pager: {
        pageNum: 1,
        page: 10,
        total: 0
      },
      action: 'create',
      roleForm: {},
      rules: {
        roleName: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ]
      },
      // 权限展示
      showPermission: false,
      curRoleName: '',
      curRoleId: '',
      menuList: [],
      // 菜单映射表
      actionMap: {}
    }
  },
  methods: {
    // 表单查询
    handleQuery() {
      this.getRoleList()
    },
    // 重置表单
    handleReset(form) {
      this.$refs[form].resetFields()
    },
    // 创建角色
    handleCreate() {
      this.action = 'create'
      this.showModal = true
    },
    // 编辑角色
    handleEdit(row) {
      this.action = 'edit'
      this.showModal = true
      this.$nextTick(() => {
        // Object.assign(this.roleForm, row)
        this.roleForm = { _id: row._id, roleName: row.roleName, remark: row.remark }
      })
    },
    // 删除角色
    async handleDel(_id) {
      await this.$api.roleOperate({ _id, action: 'delete' })
      this.$message.success('删除成功')
      this.getRoleList()
    },
    // 关闭弹窗
    handleClose() {
      this.showModal = false
      this.handleReset('dialogForm')
    },
    // 分页
    handleCurrentChange(current) {
      this.pager.pageNum = current
      this.getRoleList()
    },
    // 表单提交
    handleSubmit() {
      this.$refs.dialogForm.validate(async (valid) => {
        if (valid) {
          let { roleForm, action } = this
          let params = { ...roleForm, action }
          await this.$api.roleOperate(params)
          this.showModal = false
          this.handleReset('dialogForm')
          if (params.action === 'create') {
            this.$message.success('角色创建成功')
          }
          this.getRoleList()
        }
      })
    },
    // 弹出权限选择弹框
    handleOpenPermission(row) {
      this.curRoleName = row.roleName
      this.curRoleId = row._id
      this.showPermission = true
      let { checkedKeys } = row.permissionList
      setTimeout(() => {
        this.$refs.permissionTree.setCheckedKeys(checkedKeys)
      })
    },
    // 弹窗关闭
    handlePermissionClose() {
      this.showPermission = false
    },
    // 提交选择权限
    async handlePermissionSubmit() {
      // 目前选中节点所组成的数组
      let checkedKeys = this.$refs.permissionTree.getCheckedKeys()
      let params = {
        _id: this.curRoleId,
        permissionList: {
          checkedKeys
        }
      }

      await this.$api.updatePermission(params)
      this.showPermission = false
      this.$message.success('设置成功')
      this.getRoleList()
    },
    // 角色和 key 值之间的转换
    getActionMap(list) {
      let actionMap = {}
      const deep = (arr) => {
        while (arr.length) {
          let item = arr.pop()
          if (item.children) {
            actionMap[item._id] = item.menuName
            deep(item.children)
          } else {
            actionMap[item._id] = item.menuName
          }
        }
      }
      deep(JSON.parse(JSON.stringify(list)))
      this.actionMap = actionMap
    },
    // 角色列表初始化
    async getRoleList() {
      try {
        const res = await this.$api.getRoleList({ ...this.queryForm, ...this.pager })
        let { list, page } = res
        this.roleList = list
        this.pager = page
      } catch (e) {
        throw new Error(e)
      }
    },
    // 菜单列表初始化
    async getMenuList() {
      try {
        let list = await this.$api.getMenuList()
        this.menuList = list
        this.getActionMap(list)
      } catch (e) {
        throw new Error(e)
      }
    }
  },
  mounted() {
    this.getRoleList()
    this.getMenuList()
  }
}
</script>

<style lang="scss" scoped>
.query-form {
  display: flex;
  justify-content: space-between;
}
.el-pagination {
  text-align: center;
  padding-top: 30px;
  padding-bottom: 30px;
}
</style>
